/**
 * 工时统计筛选表单组件
 */

'use client';

import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  DatePicker,
  Select,
  Button,
  Space,
  Typography,
  Divider,
  Tag,
  Tooltip
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  FilterOutlined,
  CalendarOutlined,
  ProjectOutlined,
  TeamOutlined
} from '@ant-design/icons';
import { WorkloadStatsQueryParams } from '@/types/workloadStats';
import { useWorkloadMeta } from '@/hooks/useWorkloads';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text } = Typography;

interface WorkloadStatsFilterProps {
  onSearch: (params: WorkloadStatsQueryParams) => void;
  loading?: boolean;
}

export default function WorkloadStatsFilter({
  onSearch,
  loading = false
}: WorkloadStatsFilterProps) {
  const [form] = Form.useForm();
  const [selectedProjects, setSelectedProjects] = useState<string[]>([]);
  const [selectedMembers, setSelectedMembers] = useState<string[]>([]);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);

  const {
    projects,
    users,
    workloadTypes,
    loading: metaLoading,
    fetchProjects,
    fetchUsers,
    fetchWorkloadTypes
  } = useWorkloadMeta();

  useEffect(() => {
    // 初始化时获取元数据
    fetchProjects();
    fetchUsers();
    fetchWorkloadTypes();

    // 设置默认日期范围（最近30天）
    const defaultRange: [dayjs.Dayjs, dayjs.Dayjs] = [
      dayjs().subtract(30, 'day'),
      dayjs()
    ];
    setDateRange(defaultRange);
    form.setFieldsValue({
      dateRange: defaultRange
    });

    // 不执行默认查询，等待用户选择项目后手动查询
  }, []);

  const handleSearch = (customParams?: WorkloadStatsQueryParams) => {
    if (customParams) {
      onSearch(customParams);
      return;
    }

    form.validateFields().then(values => {
      const params: WorkloadStatsQueryParams = {};

      // 处理日期范围
      if (values.dateRange && values.dateRange.length === 2) {
        params.startDate = values.dateRange[0].format('YYYY-MM-DD');
        params.endDate = values.dateRange[1].format('YYYY-MM-DD');
      }

      // 处理项目筛选 - 必须选择至少一个项目
      if (values.projectIds && values.projectIds.length > 0) {
        params.projectIds = values.projectIds;
      } else {
        // 如果没有选择项目，提示用户
        form.setFields([
          {
            name: 'projectIds',
            errors: ['请至少选择一个项目进行统计分析']
          }
        ]);
        return;
      }

      // 处理成员筛选
      if (values.memberIds && values.memberIds.length > 0) {
        params.memberIds = values.memberIds;
      }

      // 处理工时类型筛选
      if (values.workloadTypeIds && values.workloadTypeIds.length > 0) {
        params.workloadTypeIds = values.workloadTypeIds;
      }

      console.log('工时统计查询参数：', params);
      onSearch(params);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setSelectedProjects([]);
    setSelectedMembers([]);
    
    // 重置为默认日期范围
    const defaultRange: [dayjs.Dayjs, dayjs.Dayjs] = [
      dayjs().subtract(30, 'day'),
      dayjs()
    ];
    setDateRange(defaultRange);
    form.setFieldsValue({
      dateRange: defaultRange
    });

    // 重置后不自动查询，等待用户选择项目
    onSearch({ reset: true } as any); // 传递重置标志
  };

  const handleProjectChange = (values: string[]) => {
    setSelectedProjects(values);
  };

  const handleMemberChange = (values: string[]) => {
    setSelectedMembers(values);
  };

  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null);
  };

  // 快速日期选择
  const handleQuickDateSelect = (days: number) => {
    const range: [dayjs.Dayjs, dayjs.Dayjs] = [
      dayjs().subtract(days, 'day'),
      dayjs()
    ];
    setDateRange(range);
    form.setFieldsValue({
      dateRange: range
    });
  };

  return (
    <Card 
      title={
        <Space>
          <FilterOutlined />
          <span>筛选条件</span>
          {(selectedProjects.length > 0 || selectedMembers.length > 0) && (
            <Tag color="blue">
              已选择 {selectedProjects.length + selectedMembers.length} 项筛选条件
            </Tag>
          )}
        </Space>
      }
      size="small"
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSearch}
      >
        <Row gutter={[16, 8]}>
          <Col xs={24} sm={12} md={8}>
            <Form.Item
              label={
                <Space>
                  <CalendarOutlined />
                  <span>统计时间范围</span>
                </Space>
              }
              name="dateRange"
              rules={[{ required: true, message: '请选择统计时间范围' }]}
            >
              <RangePicker
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
                placeholder={['开始日期', '结束日期']}
                onChange={handleDateRangeChange}
                allowClear={false}
              />
            </Form.Item>
            <Space wrap>
              <Button size="small" onClick={() => handleQuickDateSelect(7)}>
                最近7天
              </Button>
              <Button size="small" onClick={() => handleQuickDateSelect(30)}>
                最近30天
              </Button>
              <Button size="small" onClick={() => handleQuickDateSelect(90)}>
                最近90天
              </Button>
            </Space>
          </Col>

          <Col xs={24} sm={12} md={8}>
            <Form.Item
              label={
                <Space>
                  <ProjectOutlined />
                  <span>项目/产品</span>
                  {projects.length > 0 && (
                    <Text type="secondary">({projects.length}个)</Text>
                  )}
                </Space>
              }
              name="projectIds"
              rules={[{ required: true, message: '请至少选择一个项目进行统计' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择项目（必选，支持多选）"
                style={{ width: '100%' }}
                loading={metaLoading}
                showSearch
                filterOption={(input, option) =>
                  String(option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
                onChange={handleProjectChange}
                maxTagCount="responsive"
              >
                {projects.map(project => (
                  <Option key={project.id} value={project.id}>
                    <Tooltip title={project.identifier}>
                      {project.name}
                    </Tooltip>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8}>
            <Form.Item
              label={
                <Space>
                  <TeamOutlined />
                  <span>团队成员</span>
                  {users.length > 0 && (
                    <Text type="secondary">({users.length}个)</Text>
                  )}
                </Space>
              }
              name="memberIds"
            >
              <Select
                mode="multiple"
                placeholder="选择成员（不选择表示全部成员）"
                style={{ width: '100%' }}
                loading={metaLoading}
                showSearch
                filterOption={(input, option) =>
                  String(option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
                onChange={handleMemberChange}
                maxTagCount="responsive"
              >
                {users.map(user => (
                  <Option key={user.id} value={user.id}>
                    {user.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{ margin: '16px 0' }} />

        <Row justify="space-between" align="middle">
          <Col>
            <Space wrap>
              {dateRange && (
                <Tag icon={<CalendarOutlined />} color="blue">
                  {dateRange[0].format('MM-DD')} 至 {dateRange[1].format('MM-DD')}
                </Tag>
              )}
              {selectedProjects.length > 0 && (
                <Tag icon={<ProjectOutlined />} color="green">
                  {selectedProjects.length} 个项目
                </Tag>
              )}
              {selectedMembers.length > 0 && (
                <Tag icon={<TeamOutlined />} color="orange">
                  {selectedMembers.length} 个成员
                </Tag>
              )}
            </Space>
          </Col>
          <Col>
            <Space>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleReset}
                disabled={loading}
              >
                重置
              </Button>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={() => handleSearch()}
                loading={loading}
              >
                查询统计
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}